<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\business\controller;
use think\Db;
class Coupon extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
//        header('Access-Control-Allow-Origin:*');
//        extract(input());
//        if($user_id != 0){
//            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//            if($auth == 112){
//                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
//                exit;
//            }elseif($auth == 110){
//                echo json_encode(['status' => 302, 'msg' => $this->frost]);
//                exit;
//            }elseif($auth == 1103){
//                echo json_encode(['status' => 303, 'msg' => $this->del]);
//                exit;
//            }
//        }

    }
    
    /**
     * 首页(优惠券列表)
     */
    public function couponIndex(){
        extract(input());
        $today = date('Y-m-d');
        $where = array();
        $where['coupon_s_id'] = $user_id;
        $where['coupon_status'] = ['<>',4];
        $where['coupon_end'] = array('>=',$today);
        //1、列表
        $data = Db::table('up_shop_coupon')
            ->where($where)
            ->order('coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 优惠券详情：
     * 二维码图、是否领取，是否增送
     */
    public function couponInfo(){
        extract(input());
        $where = array();
        $where['coupon_id'] = $coupon_id;
        //1、列表
        $data = Db::table('up_shop_coupon')
            ->where($where)
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }

    /**
     * 详情下的领取明细：
     * mc_send：1是正常  2是送人了
     * mc_send_status：1是没有  2是待接受  3是已接受（不管是别人还是我）4已退还
     * @return \think\response\Json
     */
    public function couponUsers(){
        extract(input());
        $where = array();
        $where['mc_coupon_id'] = $coupon_id;
        //1、列表
        $field = 'c.*';
        $field .= ',u.user_username,u.user_phone,u2.user_username user_username2,u2.user_phone user_phone2';
        $data = Db::table('up_my_shop_coupon')->alias('c')
            ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
            ->where($where)
            ->order('mc_time DESC')
            ->page($page,20)
            ->field($field)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 发布卡券
     */
    public function couponAdd(){
        extract(input());
        $today2 = date('Y-m-d');
        $today = date('Y-m-d H:i:s');
        $insert = [
            'coupon_s_id' => $user_id,
            'coupon_name' => $coupon_name,
            'coupon_image' => $coupon_image,
            'coupon_num' => $coupon_num,
            'coupon_price' => $coupon_price, //兑换所需金币
            'coupon_money' => $coupon_money, //券的面额
            'coupon_start' => $coupon_start,
            'coupon_end' => $coupon_end,
            'coupon_use_day' => $coupon_use_day,
            'coupon_time' => $today,
            'coupon_status' => 1, //1上架   3下架
        ];
        $shop = Db::table('up_shops')->where('s_id',$user_id)->find();
        if($coupon_num <= 0 || $coupon_price <= 0){
            return json(['status'=>0,'msg'=>'数量和价格不能为0']);
        }
        if($coupon_money <= 0){
            return json(['status'=>0,'msg'=>'面额不能为0']);
        }
        if($coupon_money > $coupon_price){
            return json(['status'=>0,'msg'=>'面额不能大于兑换所需的云币']);
        }
        if($coupon_use_day <= 0){
            return json(['status'=>0,'msg'=>'使用有效期不能为0']);
        }
        if($coupon_start >= $coupon_end){
            return json(['status'=>0,'msg'=>'领取终止时间要大于起始时间']);
        }
        if($today2 >= $coupon_end){
            return json(['status'=>0,'msg'=>'领取终止时间不能少于今天']);
        }
        if($shop['s_status'] != 2){
            return json(['status'=>5,'msg'=>'未认证实名认证，去认证']);
        }
        $money = $coupon_num*$coupon_price;
        if($shop['s_money'] <= 0 || $money > $shop['s_money']){
            return json(['status'=>6,'msg'=>'金额不足，请充值']);
        }
        // 启动事务
        Db::startTrans();
        try{
            Db::name('shops')->where('s_id', $user_id)->setDec('s_money', $money);
            Db::table('up_shop_coupon')->insert($insert);
            //入商户明细和商户消息
            allInShopDetail($money, 1, $user_id, '新增卡券：' . $coupon_name,8);
            allInNotice('扣款', '您新增的卡券：' . $coupon_name . '，成功扣款' . ($money / 10) . '元！', 3, $user_id);
            Db::commit();
            return json(['status'=>200,'msg'=>'ok']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>100,'msg'=>'新增失败']);
        }
    }
   /**
     * 编辑卡券
     */
    public function couponEdit(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $today_date = date('Y-m-d');
        $update = [
            'coupon_name' => $coupon_name,
            'coupon_image' => $coupon_image,
            'coupon_time' => $today,
            'coupon_status' => $coupon_status, //1上架  3下架
        ];
        $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
        if($can['coupon_status'] != 1){
            return json(['status'=>0,'msg'=>'只有上架的卡券才可以编辑']);
        }
        if($can['coupon_status'] == 1 && $coupon_status == 3){
            $back = ($can['coupon_num'] - $can['coupon_get_num']) * $can['coupon_price'];
            if ($back > 0) {
                Db::name('shops')
                    ->where('s_id', $can['coupon_s_id'])
                    ->setInc('s_money', $back);
                //入商户明细和商户消息
                allInShopDetail($back, 2, $can['coupon_s_id'], $can['coupon_name'] . '优惠券下架退还',8);
                allInNotice('优惠券下架退还', $can['coupon_name'] . '优惠券下架退还，返还' . ($back / 10) . '元！', 3, $can['coupon_s_id']);
            }
        }
        $res = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'OK']);
        }else{
            return json(['status'=>0,'msg'=>'编辑失败']);
        }

    }
    /**
     * 下架kaquan
     * @return \think\response\Json
     */
    public function offLine(){
        extract(input());
        Db::startTrans ();
        try{
            $today = date('Y-m-d H:i:s');
            $update = [
                'coupon_time' => $today,
                'coupon_status' => 3, //1上架  3下架
            ];
            $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
            if($can['coupon_status'] != 1){
                return json(['status'=>0,'msg'=>'只有上架的卡券才可以下架']);
            }
            $back = ($can['coupon_num'] - $can['coupon_get_num']) * $can['coupon_price'];
            if ($back > 0) {
                Db::name('shops')
                    ->where('s_id', $can['coupon_s_id'])
                    ->setInc('s_money', $back);
                //入商户明细和商户消息
                allInShopDetail($back, 2, $can['coupon_s_id'], $can['coupon_name'] . '优惠券下架退还',8);
                allInNotice('优惠券下架退还', $can['coupon_name'] . '优惠券下架退还，返还' . ($back / 10) . '元！', 3, $can['coupon_s_id']);
            }
            Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
            Db::commit();
            return json(['status' => 200, 'msg' => '成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>'失败']);
        }
    }
    /**
     * 删除卡券
     */
    public function couponDel(){
        extract(input());
        $can = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->find();
        if($can['coupon_status'] == 1){
            return json(['status'=>0,'msg'=>'只有已到期或下架的卡券才可以删除']);
        }
        $update = [
            'coupon_status' => 4
        ];
        $res = Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'OK']);
        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }

    }



    //-------------------------------------------------------
    /**
     * 扫码核销
     */
    public function ercodeUse(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        if($s_id != $user_id){
            return json(['status'=>0,'msg'=>'此码不是本商户的二维码']);
        }
        $where = [
            'mc_user_id' => $uid,
            'mc_s_id' => $s_id,
            'mc_coupon_id' => $coupon_id,
        ];
        $can = Db::table('up_my_shop_coupon')->where($where)->find();
        if($can){
            if($can['mc_status'] != 1){
                return json(['status'=>0,'msg'=>'此码已经使用或者过期了']);
            }
            if($can['mc_send'] == 2 && $can['mc_send_status'] != 3){
                return json(['status'=>0,'msg'=>'此码还未被领取']);
            }
            $res = Db::table('up_my_shop_coupon')->where($where)->update([
                'mc_status' => 2,
                'mc_use_time' => $today,
            ]);
            Db::table('up_shop_coupon')->where('coupon_id',$coupon_id)->setInc('coupon_use_num');
            if($res){
                return json(['status'=>200,'msg'=>$can['mc_code']]);
            }else{
                return json(['status'=>0,'msg'=>'核销失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>'无此码信息']);
        }
    }
    /**
     * 输入码核销
     */
    public function inputUse(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            'mc_s_id' => $user_id,
            'mc_code' => $mc_code,
        ];
        $can = Db::table('up_my_shop_coupon')->where($where)->find();
        if($can){
            if($can['mc_status'] != 1){
                return json(['status'=>0,'msg'=>'此码已经使用或者过期了']);
            }
            if($can['mc_send'] == 2 && $can['mc_send_status'] != 3){
                return json(['status'=>0,'msg'=>'此码还未被领取']);
            }
            $res = Db::table('up_my_shop_coupon')->where($where)->update([
                'mc_status' => 2,
                'mc_use_time' => $today,
            ]);
            Db::table('up_shop_coupon')->where('coupon_id',$can['mc_coupon_id'])->setInc('coupon_use_num');
            if($res){
                return json(['status'=>200,'msg'=>$mc_code]);
            }else{
                return json(['status'=>0,'msg'=>'核销失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>'无此码信息']);
        }
    }
    /**
     * 核销明细：
     * mc_send：1是正常  2是送人了
     * 没送人就是u，送人的就是u2
     * @return \think\response\Json
     */
    public function allCouponUses(){
        extract(input());
        $where = array();
        $where['mc_s_id'] = $user_id;
        $where['mc_status'] = 2;
        //1、列表
        $field = 'mc_use_time,coupon_name,coupon_image,mc_ercode,mc_code,mc_send';
        $field .= ',u.user_id,u.user_username,u.user_phone,u2.user_id user_id2,u2.user_username user_username2,u2.user_phone user_phone2';
        $data = Db::table('up_my_shop_coupon')->alias('c')
            ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
            ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
            ->where($where)
            ->order('mc_use_time DESC')
            ->page($page,10)
            ->field($field)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
}